package com.aoxon.cargo.activity.n;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.activity.BaseActivity;
import com.aoxon.cargo.activity.PurSupplierDetailsActivity;
import com.aoxon.cargo.adapter.PurSupplierListAdapter;
import com.aoxon.cargo.bean.ClosePoint;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.component.MyListBottom;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.CloseSupplierService;
import com.aoxon.cargo.service.HotSupplierService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class PurSupplierCloseActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private int startIndex = 0;
	private int length = 20;
	private boolean isReachLast = false;

	private ClosePoint cp;
	private ImageView ivReturnButton;

	private int visibleLastIndex;
	private TextView tvTitle;

	private ListView lvSupplierList;

	private PurSupplierListAdapter adapter;

	private MyListBottom myListBottom;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private List<Supplier> suppliers = new ArrayList<Supplier>();
	private HotSupplierService hotSupplierService = (HotSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.HOT_SUPPLIER);
	private CloseSupplierService closeSupplierService = (CloseSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.CLOSE_SUPPLIER);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setup();
		normalDataLoader.load();
	}

	OnScrollListener myScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				adapter.setBusy(true);
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				adapter.setBusy(false);
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				int lastIndex = adapter.getCount();
				adapter.setBusy(false);

				// if (visibleLastIndex == lastIndex && !isLoading &&
				// !isReachLast) {
				// 滑动到列表底部时便加载数据
				// }

				// 滑动到列表的2/3时便加载数据
				if (visibleLastIndex >= (int) (lastIndex * 2 / 3)
						&& !isReachLast) {
					normalDataLoader.load();
				}
				break;
			default:
				break;
			}
			adapter.notifyDataSetChanged();
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			visibleLastIndex = firstVisibleItem + visibleItemCount - 1;

		}
	};

	/**
	 * 选项点击监听
	 */
	OnItemClickListener myItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if ((adapter.getCount() != position)) {
				Intent intent = new Intent(PurSupplierCloseActivity.this,
						PurSupplierDetailsActivity.class);
				intent.putExtra("strSupplier",
						DataUtil.gson.toJson(suppliers.get(position)));
				System.out.print(DataUtil.gson.toJson(suppliers.get(position)));
				startActivity(intent);
			}
		}

	};

	private void setup() {
		setContentView(R.layout.pur_close_supplier_list);
		cp = new Gson().fromJson(getIntent().getStringExtra("ClosePoint"),
				ClosePoint.class);
		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivReturnButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onKeyDown(KeyEvent.KEYCODE_BACK, null);
			}
		});

		ImageView ivGPSButton = (ImageView) findViewById(R.id.ivPublicTitleOther);
		ivGPSButton.setVisibility(View.GONE);

		RadioGroup group = (RadioGroup) findViewById(R.id.radio_button);
		group.setVisibility(View.GONE);

		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);

		lvSupplierList = (ListView) findViewById(R.id.lvPurSullierList);

		tvTitle.setText("附近商家");

		myListBottom = new MyListBottom(this, lvSupplierList);

		normalDataLoader.setOnloadDataListener(this);

		adapter = new PurSupplierListAdapter(this, suppliers, false);
		lvSupplierList.setAdapter(adapter);

		lvSupplierList.setOnScrollListener(myScrollListener);
		lvSupplierList.setOnItemClickListener(myItemClickListener);

		adapter.notifyDataSetChanged();

	}

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		myListBottom.showProgressBar();
		myListBottom.setText("加载中...");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		// isLoading = true;
		normalDataLoader.loading(true);
		GsonBean gsonBean = null;
		Log.v("CloseActivity", "131");
		gsonBean = closeSupplierService.execute(cp, startIndex, length);
		Log.v("getStrJson", gsonBean.getStrJson());
		if (CheckStateUtil.check(gsonBean)) {
			List<Supplier> supplierList = DataUtil.gson.fromJson(
					gsonBean.getStrJson(), new TypeToken<List<Supplier>>() {
					}.getType());
			startIndex += length;
			suppliers.addAll(supplierList);
			msg.what = MyStateUtil.LIST_CHANGE;
			ToastUtil.show(this, "附近没有商家，为您显示热门商家");
		} else {
			// 查找不到数据的情况
			gsonBean = hotSupplierService.execute(startIndex, length);
			if (CheckStateUtil.check(gsonBean)) {
				List<Supplier> supplierList = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<Supplier>>() {
						}.getType());
				startIndex += length;
				suppliers.addAll(supplierList);
				msg.what = MyStateUtil.LIST_CHANGE;
			} else {
				isReachLast = true;
				msg.what = MyStateUtil.LIST_IS_REACH_LAST;
			}
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		myListBottom.hideProgressBar();
		switch (state) {
		case MyStateUtil.LIST_CHANGE:
			Log.i("listChange",
					"------------------listChange--------------------");
			myListBottom.setText("向上拉加载数据");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			myListBottom.setText("无网络连接～");
			break;
		case MyStateUtil.LIST_IS_REACH_LAST:
			myListBottom.setText("没有相应数据咯～");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			myListBottom.setText("向上拉加载数据");
			break;
		default:
			break;
		}
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK && event == null)
				|| (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
			Intent intent = new Intent(getBaseContext(), PurMapActivity.class);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}
}
